/*
 *  Copyright (c) 2020-2021 Guo Limin
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.github.x19990416.mxpaas.application.admin.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CompressUtil {
  private static final byte[] _BUFF = new byte[1024];

  public static void zip(Map<String, File> toZip, File zipFile) throws IOException {
    ZipOutputStream out =
        new ZipOutputStream(new FileOutputStream(zipFile), StandardCharsets.UTF_8);
    toZip.forEach(
        (fileAbsolutePath, file) -> {
          try {
            zip(fileAbsolutePath, new FileInputStream(file), out);
          } catch (IOException e) {
            e.printStackTrace();
          }
        });
    out.close();
  }

  public static void zip(
      String fileAbsolutePath, FileInputStream in, ZipOutputStream zipFileStream) {
    try {
      zipFileStream.putNextEntry(new ZipEntry(fileAbsolutePath));
      zipFileStream.write(in.readAllBytes());
      int len;
      while ((len = in.read(_BUFF)) > 0) {
        zipFileStream.write(_BUFF, 0, len);
      }
      zipFileStream.closeEntry();
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
